<?php
namespace app\common\service\impl;
use app\common\enums\ResultEnum;
use app\common\exception\ZeduException;
use app\common\model\InstallDevices;
use app\common\model\InstallUser;
use app\common\model\InstallationLog;
use app\common\model\Terminal;
use app\common\model\Version;
use app\common\service\TerminalService;
use app\common\validate\Terminal as TerminalValidate;
use think\facade\Log;
use app\common\model\Cars;
use app\common\client\IotCloudClient;
use app\common\model\CarsInfo;

class TerminalServiceImpl implements TerminalService
{
    protected $version;
    protected $terminal;
    protected $installDevice;
    protected $installUser;
    protected $installationLog;
    protected $cars;
    protected $iotClient;
    protected $carsInfo;
    
    public function __construct(Version $version,Terminal $terminal,InstallDevices $installDevice,InstallUser $installUser,InstallationLog $installationLog,Cars $cars,IotCloudClient $iotClient,CarsInfo $carsInfo)
    {
        $this->version = $version;
        $this->terminal = $terminal;
        $this->installDevice = $installDevice;
        $this->installUser = $installUser;
        $this->installationLog = $installationLog;
        $this->cars = $cars;
        $this->iotClient = $iotClient;
        $this->carsInfo = $carsInfo;
    }
    
    public function versionAdd(array $data)
    {
        try {
            $this->version->create($data);
            return true;
        } catch (\Exception $e) {
            Log::record('[ 添加失败 ]:'.$e->getMessage(),'error');
            return false;
        }
        
    }
    public function versionList()
    {
        try {
            $version = $this->version->all();
        } catch (\Exception $e) {
            Log::record('[ 查询失败 ]:'.$e->getMessage(),'error');
            return false;
        }
        return $version;
    }
    
    public function versionDel(int $id)
    {
        try {
            $this->version->destroy($id);
            return true;
        } catch (\Exception $e) {
            Log::record('[ 删除失败 ]:'.$e->getMessage(),'error');
            return false;
        }
    }
    
    public function index(array $where, int $length, int $page)
    {
        try {
            $model = $this->terminal->where($where)->order('id', 'desc')
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
        } catch (\Exception $e) {
            Log::record('终端列表:'.$e->getMessage(),'error');
            return false;
        }
        return $model;
    }
    
    public function uploadFile(array $data)
    {
        $uploadData = [];
        $num = ['insertNum'=>0,'updateNum'=>0];
        if(!empty($data)){
            foreach ($data as $value) { 
                $uploadData['cardcode'] = trim($value[0]??'');
                $uploadData['sim_id'] = trim($value[1]??'');
                $uploadData['equipment_id'] = trim($value[2]??'');
                switch (trim($value[3]??'')) {
                    case '赛卡(博鹭途)':     
                        $uploadData['supplier_no'] = 1376920002;
                        break;
                    case '唯特迅':             
                        $uploadData['supplier_no'] = 1376920001;
                        break;
                    default:
                        $uploadData['supplier_no'] = null;
                        break;
                }
                
                switch (trim($value[4]??'')) {
                    case '已注册':              
                        $uploadData['status'] = 1;
                        break;
                    case '未注册':                   
                        $uploadData['status'] = 0;
                        break;
                    default:
                        $uploadData['status'] = null;
                        break;
                }
                $terminal = $this->terminal->where(['equipment_id'=>$uploadData['equipment_id']])->find();
                if($terminal){
                   try {
                       $this->terminal->save($uploadData,['equipment_id'=>$uploadData['equipment_id']]);
                       $num['updateNum']++;
                   } catch (\Exception $e) {
                       Log::record('[ 更新数据数据失败 ]:'.$e->getMessage(),'error');
                       return false;
                   }
                   
                }else{
                    try {
                        $this->terminal->create($uploadData);
                        $num['insertNum']++;
                    } catch (\Exception $e) {
                        Log::record('[ 写入数据失败 ]:'.$e->getMessage(),'error');
                        return false;
                    } 
                }
            }
            return $num;
        }
    }
    
    public function list(int $id){
        try {
            $data = $this->terminal->get($id);
        } catch (\Exception $e) {
            Log::record('[ 读取数据失败 ]:'.$e->getMessage(),'error');
            return false;
        }
        return $data;
    }
    
    public function edit(array $data)
    {
        $validate = new TerminalValidate;
        if(!$validate->check($data)){
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$validate->getError()]);
        }
       try {
           $this->terminal->save($data,['id'=>$data['id']]);
       } catch (\Exception $e) {
           Log::record('[ 更新数据失败 ]:'.$e->getMessage(),'error');
           return false;
       }
        return true;
    }
    
    public function upgrade(array $data)
    {
        $carId = substr($data['id'],0,strlen($data['id'])-1);
        $cars = $this->cars->where('car_id','in',$carId)->field('supplier_no,car_unique_id')->select();
        $version = $this->version->get($data['version'])->value('version');
        $num = 0;
        if($cars){
            foreach ($cars as $value){
                if($value['supplier_no'] == 1376920003){
                    $res = $this->iotClient->upgrade($value['car_unique_id'], $version);
                    if($res == false){
                        return false;
                    }
                    if($res['result']==0){
                        $num ++;
                    }
                }
            }
           
            return $num;
            
        }else{
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>"车辆不存在"]);
        }  
        
    }
    
    public function user(array $where, int $length, int $page)
    {
        try {
            $model = $this->installDevice->with('cars,installUser')->where($where)->order('id', 'desc')
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
        } catch (\Exception $e) {
            Log::record('安装人员列表:'.$e->getMessage(),'error');
            return false;
        }
        return $model;
    }
    
    public function userList()
    {
        try {
            $data = $this->installUser->field('id,name')->all();
        } catch (\Exception $e) {
            Log::record('安装人员:'.$e->getMessage(),'error');
            return false;
        }
        return $data;
    }
    
    public function userEdit(array $data)
    {
        $value = $this->installDevice->where(['id'=>$data['id']])->value($data['key']);
        try {
            $res = $this->installDevice->save([$data['key']=>$data['value']],['id'=>$data['id']]);
            if($res){
                $resLog = $this->recordLog($data,$value,$this->installDevice[$data['key']]);
                if($resLog){
                    return $this->installDevice;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        } catch (\Exception $e) {
            Log::record('[ 编辑安装人员列表 ]:'.$e->getMessage(),'error');
            return false;
        }
        
    }
    
    public function recordLog($data,$oldValue,$value){
        $type = [
            'user_id'=>1,
            'type'=>2 
        ];
       
        $log = ['installation_id'=>$data['id'],'admin_id'=>session('admin.id'),'type'=>$type[$data['key']],'old_value'=>$oldValue,'value'=>$value];
        
        try {
            $this->installationLog->create($log);
        } catch (\Exception $e) {
            Log::record('[ 写入数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        
        return true;
        
    }
    
    public function installLog(array $data)
    {
        try {
            $model = $this->installationLog::with('admin')->where(['installation_id'=>$data['id']])->order('id', 'desc')
            ->paginate($data['length'],false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$data['page'],
            ]);
        } catch (\Exception $e) {
            Log::record('[ 查询日志 ]'.$e->getMessage(),'error');
            return false;
        }
        
        return $model;
    }
    
    public function userDel(int $id)
    {
        try {
            $this->installDevice->destroy($id);
        } catch (\Exception $e) {
            Log::record('[ 删除 ]'.$e->getMessage(),'error');
            return false;
        }
        return true;
    }
    
    public function exchange(array $data)
    {
        $res = $this->iotClient->RentType($data['vin'], $data['type']);
        if($res == false){
            return false;
        }
        if($res['result']==0){
            return true;
        }else{
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$res['msg']]);
        }
    }
    
    public function searchVersion(String $version)
    {
        try {
            $data =$this->carsInfo->where('machine_version','like','%'.$version.'%')->limit(10)->select();
        } catch (\Exception $e) {
            Log::record('[ 搜索失败 ]'.$e->getMessage(),'error');
            return false;
        }
        return $data;
    }
    
    public function machineList(array $where, int $length, int $page)
    {
        try {
            $model = $this->cars->with('agency,brand,carsInfo')->where($where)
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
        } catch (\Exception $e) {
            Log::record('车机列表:'.$e->getMessage(),'error');
            return false;
        }
        return $model;
    }
    
    public function register(int $id)
    {
        try {
            $terminal = $this->terminal->field('equipment_id,status')->get($id);
        } catch (\Exception $e) {
            Log::record('查询失败:'.$e->getMessage(),'error');
            return false;
        }
        if(!$terminal){
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'设备不存在']);
        }
        
        if($terminal['status'] == 1){
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'设备已注册']);
        }
        
        $array = $this->iotClient->registerDevice($terminal['equipment_id']);
        
        if($array == false){
            return false;
        }
        
        if(!empty($array) && $array['result'] == 0){
            if($array['data'][0]['success'] == true){
                try {
                    $this->terminal->save(['status'=>1],['equipment_id'=>$terminal['equipment_id']]);
                } catch (\Exception $e) {
                    Log::record('注册状态更新:'.$e->getMessage(),'error');
                    return false;
                }
                return true;
            }else{
                try {
                    $this->terminal->save(['status'=>1],['equipment_id'=>$terminal['equipment_id']]);
                } catch (\Exception $e) {
                    Log::record('注册状态更新:'.$e->getMessage(),'error');
                    return false;
                }
                throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'设备已注册']);
            }
        }else{
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$array['msg']]);
        }
        
    }
    
    public function queryDeviceDetails(int $id)
    {
        $data = [];
        try {
            $terminal = $this->terminal->field('equipment_id')->get($id);
        } catch (\Exception $e) {
            Log::record('查询失败:'.$e->getMessage(),'error');
            return false;
        }
        
       if(empty($terminal)){
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'设备不存在']);
        }
        
       $arr = $this->iotClient->queryDetails($terminal['equipment_id']);
        
        if($arr == false){
            return false;
        }
        
        if(!empty($arr) && $arr['result']==0){
            $data['device'] = $arr['data'][0]['data'];
            $data['cars'] = $this->cars->where(['equipment_id'=>$terminal['equipment_id']])->field('car_sn,car_unique_id,supplier_no,band_status')->find();
            return $data;
        }else{
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$arr['msg']]);
        }  
        
    }
    
    public function deviceDel(int $id)
    {
        try {
            $this->terminal->destroy($id);
        } catch (\Exception $e) {
            Log::record('[ 删除 ]'.$e->getMessage(),'error');
            return false;
        }
        return true;
    }

















}

